const http = require("http");
const fs = require("fs");
let user = { username: "admin1", password: "12345" };
const server = http.createServer((req, res) => {
    res.writeHead(200, { "Content-Type": "text/html;charset=utf-8" });
    let data = "";
    switch (req.url) {
        case "/":
        case "/index":
            data = fs.readFileSync(__dirname + "/index.html", "utf8");
            break;
        case "/login":
            data = fs.readFileSync(__dirname + "/login.html", "utf8");
            fs.readFile(__dirname + "/persons.js", "utf8", function (err, data) {
                let per = JSON.parse(data);
                per.find(v => v.username == user.username && v.password == user.password) ? console.log("登陆成功") : console.log("用户名或密码错误");
            });
            break;
        case "/reg":
        case "/register":
            data = fs.readFileSync(__dirname + "/register.html", "utf8");
            reg()
            break;
        default:
            data = fs.readFileSync(__dirname + "/loading.html", "utf8");
            break;
    }
    res.end(data);
});
server.listen(80, () => {
    console.log("80服务已开启");
});





function reg() {
    let fd = fs.readFileSync(__dirname + "/persons.js", "utf8");
    let per = JSON.parse(fd);
    console.log(fd);
    let tag = per.find(v => v.username == user.username);
    if (tag) {
        console.log("已有用户");
    } else {
        console.log("注册成功");
        per.push({
            username: user.username,
            password: user.password,
        });
        fs.writeFile(__dirname + "/persons.js", JSON.stringify(per), function (err) {
            if (err) {
                console.log(err);
            } else {
                console.log("追加成功");
            }
        });
    }
}